<?php
return function () {
    $this->set('pretty');

    $ret = [
        'error' => 0,
        'msg' => ''
    ];

    $username = $_POST['username'];
    $nickname = $_POST['nickname'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    if (empty($username)) {
        $ret['error'] = 1;
        $ret['msg'] = '用户名不能为空！';
    }
    if (empty($nickname)) {
        $ret['error'] = 1;
        $ret['msg'] = '昵称不能为空！';
    }
    if (empty($email)) {
        $ret['error'] = 1;
        $ret['msg'] = '电子邮件不能为空！';
    }
    if (empty($password)) {
        $ret['error'] = 1;
        $ret['msg'] = '密码不能为空！';
    }
    if ($ret['error']) {
        $this->send($ret);
        return;
    }

    $password = md5($password);

    $sql = "SELECT id FROM user WHERE username='%s' OR email='%s'";
    $rs = $this->mysql->query($sql, $username, $email);
    if ($rs) {
        $ret['error'] = 1;
        $ret['msg'] = '用户名或电子邮件已被注册使用。';
    } else {
        $sql = "INSERT INTO user(username, nickname, email, password) VALUES('%s', '%s', '%s', '%s')";
        if ($this->mysql->exec($sql, $username, $nickname, $email, $password)) {
            $ret['msg'] = '注册新用户成功。';
        } else {
            $ret['error'] = 1;
            $ret['msg'] = '注册失败！';
        }
    }
    $this->send($ret);
};